import { ref, reactive } from 'vue';
import settings from '@/config/settings'
import { store } from '@/store'
import { message } from 'ant-design-vue'

export function useUpload() {
  const uploadState = reactive({
    viewUrl: settings.viewUrl,
    actionUrl: settings.baseUrl + "file/fileUpload",
    headers: {
      token: store.state.app.token
    },
    loading: false,
    fileList: [],
    file: {}
  })

  const filesChange = (info, cb) => {
    if (info.file.status === "uploading") {
      uploadState.loading = true
    }

    if (info.file.status === "done") {
      // Get this url from response in real world.
      uploadState.loading = false
      if (info.file && info.file.response) {
        const res = info.file.response
        if (res.code !== 300) return message.error("文件上传失败！")
        cb(info.file.response.data)
        uploadState.file = res.data[0]
      }
    }

    if (info.file.status === "error") {
      uploadState.loading = false
    }
  }

  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png"

    if (!isJpgOrPng) {
      message.error("只能上传 JPG 或 PNG 图片！")
    }

    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isLt2M) {
      message.error("图片大小必须小于 2MB!")
    }

    return isJpgOrPng && isLt2M
  }


  return {
    uploadState,
    beforeUpload,
    filesChange,
  }
}